// pages/changePassword/changePassword.js
Page({
  data: {
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',

     // 添加以下三个变量
    showOldPassword: false,
    showNewPassword: false,
    showConfirmPassword: false
  },

 // 提交修改密码
changePassword() {
  const {
    oldPassword,
    newPassword,
    confirmPassword
  } = this.data;

  // 表单验证
  if (!oldPassword) {
    wx.showToast({
      title: '请输入旧密码',
      icon: 'none'
    });
    return;
  }

  if (!newPassword) {
    wx.showToast({
      title: '请输入新密码',
      icon: 'none'
    });
    return;
  }

  if (newPassword.length < 6) {
    wx.showToast({
      title: '密码长度至少为6位',
      icon: 'none'
    });
    return;
  }

  if (!confirmPassword) {
    wx.showToast({
      title: '请确认新密码',
      icon: 'none'
    });
    return;
  }

  if (newPassword !== confirmPassword) {
    wx.showToast({
      title: '两次输入的密码不一致',
      icon: 'none'
    });
    return;
  }

  // 添加确认弹窗
  wx.showModal({
    title: '确认修改',
    content: '确定要修改密码吗？',
    success: (res) => {
      if (res.confirm) {
        this.submitPasswordChange();
      }
    }
  });
},

// 提交密码修改请求
submitPasswordChange() {
  // 显示加载中
  wx.showLoading({
    title: '修改中...',
  });

  console.log('开始调用修改密码接口');
  
  // 调用API修改密码 - 使用Promise方式
  const app = getApp();
  app.userRequest.changePassword({
    newPassword: this.data.newPassword,
    oldPassword: this.data.oldPassword
  }).then(res => {
    console.log('接口调用成功', res);
    if (res.data.code === 200) {
      wx.showToast({
        title: '密码修改成功',
        icon: 'success',
        duration: 2000,
        success: () => {
          this.setData({
            oldPassword: "",
            newPassword: "",
            confirmPassword: ""
          });
        }
      });
    } else {
      console.log('接口返回错误', res.data);
      wx.showToast({
        title: res.data.msg || '修改失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    console.log('接口调用失败', err);
    wx.showToast({
      title: err.errMsg || '网络错误，请重试',
      icon: 'none'
    });
  }).finally(() => {
    console.log('接口调用完成');
    wx.hideLoading();
  });
},
    // 添加以下三个方法
  toggleOldPasswordVisibility: function() {
    this.setData({
      showOldPassword: !this.data.showOldPassword
    });
  },

  toggleNewPasswordVisibility: function() {
    this.setData({
      showNewPassword: !this.data.showNewPassword
    });
  },

  toggleConfirmPasswordVisibility: function() {
    this.setData({
      showConfirmPassword: !this.data.showConfirmPassword
    });
  },

})